#include "mygraphicellipse.h"

#include <QDebug>

MyGraphicEllipse::MyGraphicEllipse(QWidget *parent) : QWidget(parent)
{
    // 圆的大小
    radius = 50;
    int width = radius*2+1;
    int height = radius*2+1;

    // 设置圆大小
    this->resize(width, height);

    // 构造编辑框，并设置大小
    edit = new MyLineEdit(this, width, height);
//    edit->show();

    isSelected = false;
}

int MyGraphicEllipse::getRadius()
{
    return this->radius;
}

void MyGraphicEllipse::addLineIndex(int index)
{
    lineIndexs.append(index);
}

QVector<int> MyGraphicEllipse::getLineIndex()
{
    return this->lineIndexs;
}

void MyGraphicEllipse::setSelect(bool isSelected)
{
    this->isSelected = isSelected;
    this->repaint();
}

void MyGraphicEllipse::removeLineIndex(int index)
{
    lineIndexs.removeOne(index);
}

void MyGraphicEllipse::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event)

    QPainter painter(this);
    QPen pen;

    if (isSelected) {
        pen.setStyle(Qt::DashLine);
        painter.setPen(pen);
    } else {
        pen.setStyle(Qt::SolidLine);
        painter.setPen(pen);
    }

    painter.drawEllipse(0, 0, radius*2, radius*2);
}

void MyGraphicEllipse::myMousePressEvent(QMouseEvent *event)
{
    this->firstClick = event->pos();
    this->firstClickTime = QTime::currentTime();
}

void MyGraphicEllipse::myMouseMoveEvent(QMouseEvent *event)
{
    QPoint pos = event->pos() - firstClick;

    this->move(this->pos() + pos);

    emit this->signalMove(lineIndexs);
}

void MyGraphicEllipse::myMouseReleaseEvent(QMouseEvent *event)
{
    Q_UNUSED(event)
    if (firstClickTime.msecsTo(QTime::currentTime()) < 150) { // 按住鼠标然后松开，间隔为 150ms 以内则认为是点击
        isSelected = !isSelected;
        this->repaint();

        // 发出修改信号
        emit this->signalSelectChange(this, isSelected);
    }
}

bool MyGraphicEllipse::event(QEvent *event)
{
    if (event->type() == QEvent::MouseButtonPress) {
        myMousePressEvent(dynamic_cast<QMouseEvent*>(event));
    } else if (event->type() == QEvent::MouseMove) {
        myMouseMoveEvent(dynamic_cast<QMouseEvent*>(event));
    } else if (event->type() == QEvent::MouseButtonRelease) {
        myMouseReleaseEvent(dynamic_cast<QMouseEvent*>(event));
    }

    return QWidget::event(event);
}
